package com.example.interactservice.controller;

import com.example.commom.enums.RespDescEnum;
import com.example.commom.enums.StatusCodeEnum;
import com.example.commom.exception.CustomException;
import com.example.commom.utils.JwtUtils;
import com.example.feign.client.BookClient;
import com.example.feign.result.AjaxResult;
import com.example.interactservice.entity.BookReviewsBranch;
import com.example.interactservice.entity.BookReviewsRoot;
import com.example.interactservice.service.BookReviewsBranchService;
import com.example.interactservice.service.BookReviewsRootService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 软工2104-李家强-2100770248
 * @since 2023-09-21
 */
@Slf4j
@Transactional
@RestController
@ApiOperation(value = "互动服务相关接口[子评论]")
@RequestMapping("/bookReviewsBranch")
public class BookReviewsBranchController {

    @Autowired
    private BookClient bookClient;


    @Autowired
    private BookReviewsBranchService bookReviewsBranchService;

    @Autowired
    private BookReviewsRootService bookReviewsRootService;


    @GetMapping("/{bookReviewsBranchId}")
    @ApiOperation(value = "测试接口1", notes = "通过id查询单个子评论")
    public AjaxResult getChapterById(@PathVariable("bookReviewsBranchId") Long bookReviewsBranchId,
                                     @RequestHeader("token") String token) {

        // 获取用户 id
        String userId = JwtUtils.getUserIdByToken(token);
        if (userId == null) {
            return AjaxResult.fail(StatusCodeEnum.Redirect.getCode(), StatusCodeEnum.Redirect.getMsg());
        }

        BookReviewsBranch result = bookReviewsBranchService.getReviewById(bookReviewsBranchId, userId);

        return AjaxResult.success(StatusCodeEnum.OK.getCode(),result);
    }


    /**
     *  获取指定书籍指定章节指定主评论的所有子评论
     */
    @GetMapping("/{targetBook}/{targetChapter}/{targetRootReview}/allReviews")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "targetBook", value = "书籍的id", dataType = "long",
                    paramType = "path", required = true),
            @ApiImplicitParam(name = "targetChapter", value = "书籍指定章节的id", dataType = "long",
                    paramType = "path", required = true),
            @ApiImplicitParam(name = "targetRootReview", value = "指定的主评论id", dataType = "long",
                    paramType = "path", required = true)
    })
    @ApiOperation(value = "获取指定书籍指定章节指定主评论下的所有子评论", notes = "参数是书籍id,章节id和主评论id")
    public AjaxResult getAllBranchReviews(@PathVariable("targetBook") Long targetBook,
                                          @PathVariable("targetChapter") Long targetChapter,
                                          @PathVariable("targetRootReview") Long targetRootReview,
                                          @RequestHeader("token") String token) {

        // 获取登录用户的 id
        String userId = JwtUtils.getUserIdByToken(token);
        if (userId == null) {
            return AjaxResult.fail(StatusCodeEnum.Redirect.getCode(), StatusCodeEnum.Redirect.getMsg());
        }

        if (targetBook == null || targetChapter == null || targetRootReview == null) {
            return AjaxResult.fail(StatusCodeEnum.FAILED.getCode(), RespDescEnum.MissRequiredParameter.getValue());
        }

        List<BookReviewsBranch> result = bookReviewsBranchService.getAllBranchReviews(targetBook,
                                         targetChapter, targetRootReview, userId);

        return AjaxResult.success(StatusCodeEnum.OK.getCode(), result);
    }

    /**
     *  插入一条指定书籍指定章节指定主评论下的子评论
     */
    @PostMapping("/insertBranchReview")
    @ApiOperation(value = "插入一条指定书籍指定章节指定主评论下的子评论", notes = "参数是子评论对象")
    public AjaxResult insertOneBranchReview(@Validated @RequestBody BookReviewsBranch bookReviewsBranch,
                                            @RequestHeader("token") String token) {


        // 参数校验: 书籍ID, 章节ID 是否是正确的?
        boolean bookIsExist = bookClient.bookIsExist(bookReviewsBranch.getBookId(), bookReviewsBranch.getChapterId());
        if (!bookIsExist) {
            // ID 不正确
            return AjaxResult.fail(RespDescEnum.MissRequiredParameter.getValue());
        }

        // 权限检查: 发送评论的用户是否是登录用户
        String tokenUsername = JwtUtils.getUserNameByToken(token);

        if (tokenUsername == null) {
            return AjaxResult.fail(StatusCodeEnum.Redirect.getCode(), StatusCodeEnum.Redirect.getMsg());
        }

        if (!bookReviewsBranch.getReader1Name().equals(tokenUsername)) {
            return AjaxResult.fail(StatusCodeEnum.UNAUTHORIZED.getCode(), StatusCodeEnum.UNAUTHORIZED.getMsg());
        }

        // 参数校验: 主评论 ID 是否正确
        BookReviewsRoot bookReviewsRootById = bookReviewsRootService.getById(bookReviewsBranch.getReviewRootId());
        if (bookReviewsRootById == null) {
            return AjaxResult.fail(RespDescEnum.MissRequiredParameter.getValue());
        }

        // 执行插入操作.
        boolean success = bookReviewsBranchService.insertBranchReview(bookReviewsBranch);

        if (success) {
            return AjaxResult.success(StatusCodeEnum.OK.getMsg());
        } else {
            throw new CustomException(StatusCodeEnum.FAILED.getMsg(), -1);
        }
    }


    /**
     *  删除一条子评论
     */
    @PostMapping("/deleteBranchReview/{targetId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "targetId", value = "子评论id", dataType = "long",
                    paramType = "path", required = true)
    })
    @ApiOperation(value = "删除一条指定书籍指定章节指定主评论下的子评论", notes = "参数是子评论对象")
    public AjaxResult deleteBranchReview(@PathVariable("targetId") Long targetId,
                                            @RequestHeader("token") String token) {

        // 判空
        if (targetId == null) {
            return AjaxResult.fail(RespDescEnum.MissRequiredParameter.getValue());
        }

        // 通过 id 查询具体的评论信息
        BookReviewsBranch bookReviewsBranch = bookReviewsBranchService.getById(targetId);
        if (bookReviewsBranch == null) {
            // 无效的id
            return AjaxResult.fail(RespDescEnum.MissRequiredParameter.getValue());
        }

        // 通过评论的 bookId 查询书籍作者
        String author = bookClient.getAuthorByBookId(bookReviewsBranch.getBookId());
        if (author == null) {
            return AjaxResult.fail(RespDescEnum.MissRequiredParameter.getValue());
        }

        // 1. 获取登录的用户名
        String tokenUsername = JwtUtils.getUserNameByToken(token);
        // 2. 判断是否具有权限
        // 权限判断, 只有书籍作者 和 评论作者才可以删除
        if (!bookReviewsBranch.getReader1Name().equals(tokenUsername)
                && !author.equals(tokenUsername)) {
            // 权限不足
            return AjaxResult.fail(StatusCodeEnum.UNAUTHORIZED.getCode(), StatusCodeEnum.UNAUTHORIZED.getMsg());
        }

        // 执行删除操作
        boolean success = bookReviewsBranchService.removeById(targetId);
        if (success) {
            return AjaxResult.success(StatusCodeEnum.OK.getMsg());
        } else {
            throw new CustomException(StatusCodeEnum.FAILED.getMsg(), -1);
        }
    }

    /**
     * 用户点赞 or 取消点赞某一条子评论
     */
    @PostMapping("/likeReview/{targetId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "targetId", value = "评论id", dataType = "long",
                    paramType = "path", required = true)
    })
    @ApiOperation(value = "用户点赞 or 取消点赞某一条主评论", notes = "参数是子评论id")
    public AjaxResult likeReview(@PathVariable("targetId") Long targetId,
                                 @RequestHeader("token") String token) {

        return bookReviewsBranchService.likeReview(targetId, token);
    }

}
